﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BlogManager.Application.Controls
{
    public partial class Tags : System.Web.UI.UserControl
    {
        public int SiteId { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["SiteId"]))
                SiteId = Convert.ToInt32(Request.QueryString["SiteId"]);

            if (!IsPostBack)
                loadTags();
        }

        protected void ImageButtonForAddigTags_Click(object sender, EventArgs e)
        {
            var tag = new BlogManager.Data.Entities.Blog_Tag();
            tag.SiteId = SiteId;
            tag.Name = TextBoxForTagName.Text;
            tag.Save();

            ReBind();

            //Finally clear the textbox...
            TextBoxForTagName.Text = "";
        }

        protected void ReBind()
        {
            CheckBoxListForSelectingTags.Items.Clear();
            loadTags();

        }

        protected void loadTags()
        {
            var tags = BlogManager.Data.Entities.Blog_Tag.All().Where(x => x.SiteId == SiteId).OrderBy(x => x.Name);
            CheckBoxListForSelectingTags.DataSource = tags;
            CheckBoxListForSelectingTags.DataValueField = Data.Entities.Blog_TagsTable.IdColumn;
            CheckBoxListForSelectingTags.DataTextField = BlogManager.Data.Entities.Blog_TagsTable.NameColumn;
            CheckBoxListForSelectingTags.DataBind();

            setSelected();
        }

        protected void setSelected()
        {
            if (_selectedTags.Count > 0)
                foreach (var category in _selectedTags)
                    for (var i = 0; i < CheckBoxListForSelectingTags.Items.Count; i++)
                        if (CheckBoxListForSelectingTags.Items[i].Value == category.ToString())
                        {
                            CheckBoxListForSelectingTags.Items[i].Selected = true;
                            break;
                        }
        }

        private List<long> _selectedTags = new List<long>();

        public List<long> SelectedTags
        {
            get
            {
                var res = new List<long>();

                for (var i = 0; i < CheckBoxListForSelectingTags.Items.Count; i++)
                {
                    if (CheckBoxListForSelectingTags.Items[i].Selected)
                        res.Add(Convert.ToInt32(CheckBoxListForSelectingTags.Items[i].Value));
                }

                return res;
            }

            set
            {
                _selectedTags = value;


            }
        }


    }
}